//
// Created by masaikk on 2020/12/7.
//

#ifndef COLK_H7_1_H
#define COLK_H7_1_H

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;
class Solution {
public:
    int matrixScore(vector<vector<int>>& A) {
        if(A.size()==1&&A[0].size()==1){
            return 1;
        } else{
            int matrixSocre=0;
            for(int i=0;i<A.size();i++){
                this->checkAndReverseRow(A[i]);
            };
            for (int i = 0; i < A[0].size(); ++i) {
                this->checkAndReserveCol(A,i);
            };
            for(int i=0;i<A.size();i++){
                matrixSocre+=this->calculateRowScore(A[i]);
            };
            return matrixSocre;
        }
    }

    static bool checkRowFirstZero(vector<int> & row){
        if(row[0]==0){
            return true;
        }
        return false;
    }

    static void reverseRow(vector<int> &row){
        for(int & i : row){
            i=1-i;
        }
    }
    void checkAndReverseRow(vector<int> &row){
        if(this->checkRowFirstZero(row)){
            this->reverseRow(row);
        }
    }
    static int calculateRowScore(vector<int> &row){
        int size=row.size();
        int times=row.size()-1;
        int rowSocre=0;
        for(int time=times;time>=0;time--){
            int tempScore=row[size-time-1]*(pow(2,time));
//            cout<<row[size-time-1]<<" "<<time<<endl;
            rowSocre+=tempScore;
        }
        return rowSocre;

    }

    static bool chechColZeroMoreThanOne(vector<vector<int>>& A,int col){
        int zeros=0;
        int ones=0;
        for (int i = 0; i < A.size(); ++i) {
            if(A[i][col]){
                ones+=1;
            } else{
                zeros+=1;
            }
        }
        if(zeros>ones){
            return true;
        } else{
            return false;
        };

    }
    static void reserveCol(vector<vector<int>>& A,int col){
//        int rowSize=A[0].size();
        int colSize=A.size();
        for(int temp=0;temp<colSize;temp++){
            A[temp][col]=1-A[temp][col];
        }
    }

    void checkAndReserveCol(vector<vector<int>>& A,int col){
        if(this->chechColZeroMoreThanOne(A,col)){
            this->reserveCol(A,col);
        }

    }
    void showMatric(vector<vector<int>>& A){
        for(int i=0;i<A.size();i++){
            for (int j = 0; j < A[0].size(); ++j) {
                cout<<A[i][j]<<" ";
            }
            cout<<endl;
        }
    }
};

#endif //COLK_H7_1_H
